from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os, logging
import model
from google.appengine.ext import db
from django.utils import simplejson
from google.appengine.api import memcache
from gae_db_manager import GaeDbManager


        
class ProjectEditorHandler(webapp.RequestHandler):

    def get(self):
        memcache.flush_all()
        action = self.request.get('action')
        if action=='read':
            options = {'tableid': 'dlz_project_list', 'where': '', 'sort': 'client_name', 'dir': 'ASC', 'limit': '', 'start': ''}
            table_model = model.dlz_project_list
            gdm = GaeDbManager('dlz_project_list')
            #results = model.get_ext_store(options, table_model)
            results = gdm.query(options, 'extjson')
            #change the idproperty
            results['metaData']['fields'].append({'header': 'google_key', 'type': 'String', 'name': 'google_key', 'dataIndex': 'google_key'})
            results['metaData']['idProperty'] = 'google_key'
            
            del results['metaData']
            self.response.headers["Content-Type"] = "application/json"  
            self.response.out.write(simplejson.dumps(results))
            #self.response.out.write('''{"success":true,"message":"Loaded data","data":[{"id":1,"first":"Fred","last":"Flintstone","email":"fred@flintstone.com"},{"id":2,"first":"Wilma","last":"Flintstone","email":"wilma@flintstone.com"},{"id":3,"first":"Pebbles","last":"Flintstone","email":"pebbles@flintstone.com"},{"id":4,"first":"Barney","last":"Rubble","email":"barney@rubble.com"},{"id":5,"first":"Betty","last":"Rubble","email":"betty@rubble.com"},{"id":6,"first":"BamBam","last":"Rubble","email":"bambam@rubble.com"}]}''')
        elif action=='create':
            self.create()
        elif action=='delete':
            self.delete()
        elif action=='update':
            self.put()
        else:
            path = os.path.join(os.path.dirname(__file__), 'template/project_editor.html')
            self.response.out.write(template.render(path, {}))
    def put(self):
        data = simplejson.loads(self.request.body)['rows']
        
        gdm = GaeDbManager('dlz_project_list')
        gdm.update([data], [])
        results = {"success":True,"message":"Updated project %s " % data['google_key'],"data": data}       
        self.response.out.write(simplejson.dumps(results))
        #self.response.out.write('{"success":true,"message":"Updated User 6","data":{"id":6,"first":"BamBam","last":"Rubble","email":"bambamasdf@rubble.com"}}')
    def create(self):
        data = simplejson.loads(self.request.body)['rows']
        gdm = GaeDbManager('dlz_project_list')
        gdm.insert([data], False, ['project_number'])
        results = {"success":True,"message":"Created record","rows": data}
        self.response.headers["Content-Type"] = "application/json"  
        self.response.out.write(simplejson.dumps(results))
    def post(self):
        self.get()
        
    def delete(self):
        key = data = simplejson.loads(self.request.body)['rows']
        logging.info(key)
        
        record = db.get(key)
        record.delete()
        self.response.out.write('{"success":true,"message":"Destroyed User 1","data":[]}')